/**
 * @Description: 菜单管理
 * @author dazer
 * @date 2019/3/5 下午17:21
 */
import React, { Fragment } from 'react';
import {
  Button,
  Card,
  Checkbox,
  Col,
  Form,
  Input,
  Radio,
  Row,
  Select,
  Spin,
  Tag,
  BackTop,
	Tooltip,
	Icon,
	Divider
} from 'antd';
import { formatMessage, FormattedMessage } from 'umi/locale';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '../../components/ourslook/BaseForm';
import ETable from '../../components/ourslook/ETable';
import { getWebPath } from '../../utils/request';
import uiUtils, { hasPermission } from '../../utils/uiUtils';
import styles from '../../utils/ourslook.less';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(() => ({}))
class Schedule extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => `${index + 1}`,
    },
    {
      title: '任务ID',
      width: 80,
      dataIndex: 'jobId',
      align: 'left',
      fixed: 'left',
      sorter: true,
    },
    { title: 'bean名称', dataIndex: 'beanName', width: 120, align: 'center', sorter: false },
    { title: '方法名称', dataIndex: 'methodName', width: 160, align: 'center', sorter: false },
    { title: '参数', dataIndex: 'params', width: 150, align: 'center', sorter: false },
    {
      title: 'cron表达式',
      dataIndex: 'cronExpression',
      width: 120,
      align: 'center',
      sorter: false,
    },
    { title: '备注', dataIndex: 'remark', align: 'center', sorter: false },
    {
      title: '状态',
      dataIndex: 'status',
      width: 30,
      align: 'center',
      render: (value, record, index) =>
        value === 0 ? (
          <Tag style={{ cursor: 'default' }} className={styles.label_success}>
            正常
          </Tag>
        ) : (
          <Tag style={{ cursor: 'default' }} className={styles.label_danger}>
            暂停
          </Tag>
        ),
    },
		{
		  title: '操作',
		  dataIndex: '',
		  width: 80,
		  align: 'center',
		  fixed: 'right',
		  render: (value, record, index) => (
		    <React.Fragment>
		      <a
		        onClick={() => {
		          this.setStateByTableColume(record, index);
		          this.view();
		        }}
		      >
		        <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看"/>}>
		          <Icon type="info"/>
		        </Tooltip>
		      </a>
		       <Divider type="vertical"/>
		      <a
		        onClick={() => {
		          this.setStateByTableColume(record, index);
		          this.update();
		        }}
		      >
		        <Tooltip title={<FormattedMessage id="ours.curd.list.update" defaultMessage="修改"/>}>
		          <Icon type="edit"/>
		        </Tooltip>
		      </a>
		    </React.Fragment>
		  ),
		}
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: Schedule.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
      menuList: [],
    };
  }

  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'beanName',
      label: 'bean名称',
      placeholder: 'bean名称',
    },
  ];

  componentDidMount() {
    this.requestList();
  }

  componentWillUnmount() {}

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({ id: 'ours.curd.list.create' }), //创建
      editModel: {},
      showList: 2,
    });
  };

  update = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />,
      editModel: JSON.parse(JSON.stringify(selectedRows[0])),
      showList: 2,
    });
    this.getInfo(selectedRows[0].jobId);
  };

  view = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].jobId);
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const jobIds = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      jobIds.push(selectedRows[i].jobId);
    }

    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-delete' }), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath('/sys/menu/delete')}`, {
        method: 'POST',
        body: jobIds,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const schedule = Object.assign(this.state.editModel, this.editForm.props.form.getFieldsValue());

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url = schedule.jobId == null ? '/sys/schedule/save' : '/sys/schedule/update';
        //对象删除一个属性
        delete schedule.cronExpressions;

        this.setState({
          editModelConfirmLoading: true,
        });
        requestPromise(`${getWebPath(url)}`, {
          method: 'POST',
          body: schedule,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            this.setState({
              showList: 1,
            });

            //新增重新置为第一页
            if (!schedule.jobId) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  getInfo = jobId => {};

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.jobId],
      selectedIndexs: [index],
    };
  };

  pause = () => {
    const selectedRows = this.state.selectedRows;
    const jobIds = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      jobIds.push(selectedRows[i].jobId);
    }

    uiUtils.showConfirm('确定要暂停选中的记录？', () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath('/sys/schedule/pause')}`, {
        method: 'POST',
        body: jobIds,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  resume = () => {
    const selectedRows = this.state.selectedRows;
    const jobIds = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      jobIds.push(selectedRows[i].jobId);
    }

    uiUtils.showConfirm('确定要恢复选中的记录？', () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath('/sys/schedule/resume')}`, {
        method: 'POST',
        body: jobIds,
      }).then(res => {
        this.setState({
          editModelCloadingonfirmLoading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  runOnce = () => {
    const selectedRows = this.state.selectedRows;
    const jobIds = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      jobIds.push(selectedRows[i].jobId);
    }

    uiUtils.showConfirm('确定要立即执行选中的记录？', () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath('/sys/schedule/run')}`, {
        method: 'POST',
        body: jobIds,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  cronNotes = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      loading: true,
    });
    requestPromise(`${getWebPath(`/sys/schedule/cronNotes/${selectedRows[0].jobId}`)}`, {
      method: 'GET',
    }).then(res => {
      this.setState({
        loading: false,
      });
      if (res && res.code === 0) {
        const cornNote = res.cornNote;
        const json = JSON.parse(cornNote);
        uiUtils.showAlert(json.description, 'info');
      }
    });
  };

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath('/sys/schedule/list')}`, this.params);
  };

  vShow = showListNum => ({ display: this.state.showList === showListNum ? 'block' : 'none' });

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{ ...this.vShow(1) }}
          className={styles.oursCard}
          bodyStyle={{ padding: '20px' }}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('sys:schedule:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增" />
            </Button>
            <Button
              type="danger"
              icon="delete"
              {...style}
              onClick={this.del}
              hidden={!hasPermission('sys:schedule:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />
            </Button>
            <Button
              type="default"
              icon="pause"
              {...style}
              onClick={this.pause}
              hidden={!hasPermission('sys:schedule:pause')}
            >
              暂停
            </Button>
            <Button
              type="default"
              icon="desktop"
              {...style}
              onClick={this.resume}
              hidden={!hasPermission('sys:schedule:resume')}
            >
              恢复
            </Button>
            <Button
              type="default"
              icon="arrow-right"
              {...style}
              onClick={this.runOnce}
              hidden={!hasPermission('sys:schedule:run')}
            >
              立即执行
            </Button>
            <Button
              type="default"
              icon="info"
              {...style}
              onClick={this.cronNotes}
              hidden={
                !(hasPermission('sys:schedule:cronNotes') || hasPermission('sys:schedule:info'))
              }
            >
              cron含义
            </Button>
            <Button
              type="default"
              icon="question"
              {...style}
              onClick={this.cronNotes}
              // hidden={!hasPermission('sys:schedule:log')}
              hidden
            >
              日志列表
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="menuId"
              selectedIndexs={this.state.selectedIndexs}
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{ x: 1055 }}
            />
          </div>
        </Card>

        <BackTop />

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
          this.state.showList === 1 ? null : (
            <Card
              title={this.state.editModalTitle}
              bordered={false}
              actions={[
                <div>
                  <React.Fragment>
                    <Button
                      type="primary"
                      hidden={this.state.editModalType === 'view'}
                      style={{ marginRight: '18px' }}
                      onClick={this.saveOrUpdate}
                    >
                      <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
                    </Button>
                    <Button
                      style={{ marginRight: '18px' }}
                      onClick={() => {
                        this.editForm.props.form.resetFields();
                        this.setState({ showList: 1 });
                      }}
                    >
                      <FormattedMessage id="ours.curd.add.back" defaultMessage="返回" />
                    </Button>
                  </React.Fragment>
                </div>,
              ]}
              style={{ ...this.vShow(2) }}
              bodyStyle={{ padding: '20px' }}
              ref={node => {
                this.container = node;
              }}
            >
              <EditForm
                type={this.state.editModalType}
                model={this.state.editModel}
                wrappedComponentRef={inst => {
                  this.editForm = inst;
                }}
              />
            </Card>
          )}
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default Schedule;

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  //MenuType：0-->目录;1-->菜单;2-->按钮

  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
    menuList: PropTypes.object,
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
    menuList: [],
  };

  constructor(props) {
    super(props);
    this.state = {};
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {
    if (nextProps.model) {
      this.state = {};
    }
  }
	setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };
  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  cronOnChange = (value, options) => {
    //段大志修改
    this.props.model.cronExpression = value;
    this.props.form.setFieldsValue({ cronExpression: value });
  };

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };
    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Form layout="horizontal">
        <Row gutter={{ ...rowGutterPxLayout }}>
          <Col {...colSpanLayout}>
            <FormItem label="bean名称" {...formItemLayout}>
              {type === 'view'
                ? model.beanName
                : getFieldDecorator('beanName', {
                    initialValue: model.beanName,
                    rules: [
                      {
                        required: true,
                        message: 'bean名称必填',
                      },
                      {
                        whitespace: true,
                        message: '不能包含空白符',
                      },
                      {
                        max: 20,
                        message: '长度不在范围内',
                      },
                    ],
                  })(
                    <Input
                      type="text"
                      autocomplete="off"
                      maxLength={20}
                      placeholder="spring bean名称，如：sysTask"
                    />
                  )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="方法名称" {...formItemLayout}>
              {type === 'view'
                ? model.methodName
                : getFieldDecorator('methodName', {
                    initialValue: model.methodName,
                    rules: [
                      {
                        required: true,
                        message: '方法名称必填',
                      },
                      {
                        whitespace: true,
                        message: '不能包含空白符',
                      },
                      {
                        max: 50,
                        message: '长度不在范围内',
                      },
                    ],
                  })(
                    <Input type="text" autocomplete="off" maxLength={50} placeholder="方法名称" />
                  )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="参数" {...formItemLayout}>
              {type === 'view'
                ? model.params
                : getFieldDecorator('params', {
                    initialValue: model.params,
                    rules: [
                      {
                        whitespace: true,
                        message: '不能包含空白符',
                      },
                      {
                        max: 30,
                        message: '长度不在范围内',
                      },
                    ],
                  })(<Input type="text" autocomplete="off" maxLength={30} placeholder="参数" />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="cron表达式" {...formItemLayout}>
              {type === 'view'
                ? model.cronExpression
                : getFieldDecorator('cronExpression', {
                    initialValue: model.cronExpression,
                    rules: [
                      {
                        required: true,
                        message: 'cron表达式必填',
                      },
                      {
                        whitespace: true,
                        message: '不能包含空白符',
                      },
                      {
                        max: 30,
                        message: '长度不在范围内',
                      },
                    ],
                  })(
                    <Input
                      type="text"
                      autocomplete="off"
                      maxLength={30}
                      placeholder="如：0 0 12 * * ?"
                    />
                  )}
              {type !== 'view' ? (
                <Fragment>
                  <code style={{ marginTop: '4px', display: 'block' }}>
                    获取cron：
                    <a href="http://cron.qqe2.com/" rel="noreferrer noopener" target="_blank">
                      cronmaker
                    </a>
                  </code>
                  {getFieldDecorator('cronExpressions', {
                    initialValue: '',
                  })(
                    <Select
                      style={{ width: '100%' }}
                      placeholder="cron表达式"
                      value=""
                      onChange={this.cronOnChange}
                    >
                      <option value="">请选择常用cron表达式</option>
                      <option value="0/30 * * * * ? *">每30秒触发一次</option>
                      <option value="0 0/1 * * * ? ">每1min触发一次</option>
                      <option value="0 0/10 * * * ? ">每10min触发一次</option>
                      <option value="0 0 2 * * ? ">每天的2点触发</option>
                      <option value="0 5 16 1/1 * ? *">每天下午15:05分触发</option>
                      <option value="58 59 23 8 3 ? 2018-2018*">
                        2018年3月8日23:59:58執行一次
                      </option>
                    </Select>
                  )}
                </Fragment>
              ) : (
                ''
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="备注" {...formItemLayout}>
              {type === 'view'
                ? model.remark
                : getFieldDecorator('remark', {
                    initialValue: model.remark,
                    rules: [
                      {
                        max: 200,
                        message: '长度不在范围内',
                      },
                    ],
                  })(
                    <TextArea
                      autosize={{ minRows: 3, maxRows: 6 }}
                      maxLength={200}
                      placeholder="备注"
                    />
                  )}
            </FormItem>
          </Col>
        </Row>
      </Form>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
